<template>
  <div>
    <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
      @change="handleImportExcel">
      <a-button type="primary" icon="import">导入</a-button>
    </a-upload>
    <div class="importInstruct">
      <a-menu style="width: 300px" :open-keys.sync="openKeys" mode="inline" v-model="selectedKeys" @click="handleClick">
        <!-- <a-sub-menu key="sub2" @titleClick="titleClick">
        <span slot="title">
          <span>二级菜单</span>
        </span>
        <a-menu-item key="5">Option 5</a-menu-item>
        <a-menu-item key="6">Option 6</a-menu-item>
        </a-sub-menu>-->
        <a-sub-menu @titleClick="titleClick" v-for="(item, index) in subData" :key="item.label">
          <span slot="title">
            <span>{{ item.title }}</span>
          </span>
          <a-menu-item v-for="(i, indx) in item.commands" :key="i.name">{{ i.name }}</a-menu-item>
        </a-sub-menu>

        <a-menu-item key="自定义指令">自定义指令</a-menu-item>
      </a-menu>
      <div class="instructionContentBox">
        <p>
          <a-textarea v-model="instructionContent" :auto-size="{ minRows: 30, maxRows: 40 }" />
          <a-select placeholder="请选择发送链接" v-model="channelId" style="width: 160px">
            <a-select-option v-for="item in channelList" :key="item.id"
              :value="item.id">{{ item.channelName }}</a-select-option>
          </a-select>
        </p>
        <p style="width: 100%;text-align: right;">
          <a-button style="margin-right:20px">取消</a-button>
          <a-button type="primary" @click="sendInstructionContent">发送</a-button>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { httpAction,getAction } from '@/api/manage'
export default {
  name: 'customInstructionImport',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      instructionContent: '',
      fileList: [],
      channelId: undefined,
      channelList: [],
      uploading: false,
      openKeys: ['xx2'],//当前展开
      selectedKeys: ['x2-1指令'],//当前选中
      subData: [
        // { title: 'a(1).xlsx', commands: [{ name: "x1-1指令", content: '2222' }, { name: "x1-2指令", content: '222322' }] },
        // { title: 'xx2', commands: [{ name: "x2-1指令", content: '22422' }, { name: "x2-2指令", content: '22122' }] },
      ],
      packageCode: '自定义指令导入',
      url: {
        channelList: '/channel/nmcChannelInfo/list',
        sendInstruction: '/channel/nmcChannelInfo/noFlowSendPackage2',
        importExcelUrl: '/command/importExcel',
      },
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    this.getChannalList()
  },
  methods: {
    getChannalList() {
      getAction(this.url.channelList).then(res => {
        if (res.success) {
          this.channelList = res.result.records
        }
      })
    },
    setD(arr, name) {
      let newarr = []
      arr.forEach(i => {
        let flag = true
        newarr.forEach(j => {
          if (i[name] == j[name]) {
            flag = false
          }
        })
        if (flag) {
          newarr.push(i)
        }
      })
      return newarr
    },
    sendInstructionContent() {
      if (!this.instructionContent) {
        this.$message.error('指令内容不能为空')
        return
      }

      // 非944字节的数据会导致业管乱掉
      if (this.instructionContent.length !== 1888) {
        this.$message.error('指令内容长度为：' + this.instructionContent.length + "(只允许发送944长度的自定义指令发送!)");
        return;
      }

      if (!this.channelId) {
        this.$message.error('请选择发送连接')
        return
      }
      let data = {
        "hexString": this.instructionContent,
        "channelId": this.channelId
      }
      httpAction(this.url.sendInstruction, data, 'post').then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        // this.instructionContent = res.reslut
        // this.$emit('setInstructionContent', res.reslut)
        //传给父组件instructionContent
      })
    },
    handleClick(e) {
      console.log('click', e);
      this.packageCode = e.key
      // this.instructionContent =
      this.subData.forEach(i => {
        this.instructionContent = i.commands.find(j => j.name == e.key).content
      })
      //每次点击要重新获取该指令的值
    },
    titleClick(e) {
      console.log('titleClick', e);

    },
    loadData() {
      console.log('-------导入后调')
    },
    /* 导入 */
    handleImportExcel(info) {
      this.loading = true;
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.loading = false;
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                <span>{msg}</span><br />
                <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
              </div>
              )
            })
          } else {
            // console.log(info.file.response.result)
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
            let infoData = info.file.response.result
            if (this.subData.find(i => i.title == infoData.title)) {
              this.subData.forEach((i, index) => {
                if (i.title == infoData.title) {
                  //有文件名重复的，扩充指令就行
                  let json = i.commands.concat(infoData.commands); //两个数组对象合并
                  let newJson = []; //盛放去重后数据的新数组
                  i.commands = [...this.setD(json, 'name')]
                  return
                }
              })
            } else {
              this.subData.push(infoData)
            }
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`);
        }
      } else if (info.file.status === 'error') {
        this.loading = false;
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes("Token失效")) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload();
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files[]', file);
      });
      this.uploading = true;

      // You can use any AJAX library you like
      // reqwest({
      //   url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      //   method: 'post',
      //   processData: false,
      //   data: formData,
      //   success: () => {
      //     this.fileList = [];
      //     this.uploading = false;
      //     this.$message.success('upload successfully.');
      //   },
      //   error: () => {
      //     this.uploading = false;
      //     this.$message.error('upload failed.');
      //   },
      // });
    },
  },
};
</script>

<style lang='less' scoped>
.importInstruct {
  display: flex;
  width: 100%;

  .instructionContentBox {
    width: calc(100% - 300px);
    // border: 1px solid #1a7683;
  }
}
</style>
